import React, { useContext, useState, useEffect, useRef } from 'react';
import { Input, Form, Select } from 'antd';
import { getMessage } from '@inbiz/react';
import { EditableContext } from './TableContent';

interface Item {
  createTime: string;
  id: string;
  moveControl: string;
  moveControlId: string;
  pcControl: string;
  pcControlId: string;
  ralationId: string;
  ralationName: string;
  remark: string;
  type: string;
  varName: string;
}

// 可修改表格组件-行
const EditableRow = (props: any) => <tr {...props} />;

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: string;
  record: Item;
  variateId: string;
  pcControl: any[];
  h5Control: any[];
  required: boolean;
  setNowKey: (b: string) => void;
  handleSave: (record: Item) => void;
  callBackEvents: {
    setPcAutoRemark?: (info: { name: string; value: string }) => string
    setH5AutoRemark?: (info: { name: string; value: string }) => string
  }
}

// 可修改表格组件-列（单元格）
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  required,
  variateId,
  pcControl,
  h5Control,
  setNowKey,
  handleSave,
  callBackEvents,
  ...restProps
}: EditableCellProps) => {
  const [editing, $Editing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing && inputRef.current) {
      let dom: HTMLElement = inputRef.current;
      dom?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setNowKey(record.id);
    $Editing(true);
    // @ts-ignore
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const getName = (id: any, isPc: boolean) => {
    let name = '';
    const arr = isPc ? pcControl : h5Control;
    let idx = arr.findIndex((i) => i.value == id);
    if (idx > -1) {
      name = arr[idx].name;
    }
    return name;
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      let row: any = { ...record };
      let remark: any = {}
      if (values.moveControlId) {
        const newName: string = getName(values.moveControlId, false);
        if (row.moveControl !== newName) {
          row.moveControl = newName
          const txt = callBackEvents?.setH5AutoRemark?.({
            value: values.moveControlId,
            name: newName
          })
          if (txt) remark.remark = txt
        }
      }
      if (values.pcControlId) {
        const newName: string = getName(values.pcControlId, true);
        if (row.pcControl !== newName) {
          row.pcControl = newName
          const txt = callBackEvents?.setPcAutoRemark?.({
            value: values.pcControlId,
            name: newName
          })
          if (txt) remark.remark = txt
        }
      }
      // 改变控件类型
      if (values.moveControlId || values.pcControlId) {
        row.type = '1'
      }
      let recordD = { ...row, ...remark, ...values };
      if (!recordD.pcControlId) {
        recordD.pcControl = ''
      }
      if (!recordD.moveControlId) {
        recordD.moveControl = ''
      }
      recordD.type = !recordD.pcControlId && !recordD.moveControlId ? '0' : '1'
      handleSave(recordD);
    } catch (err) { }
    $Editing(false);
  };

  let childNode = children;

  if (editable) {
    const nameLengthMessage = getMessage('ProcessManage.name_length_message');
    const placeMessage = getMessage('ProcessManage.placeMessage');
    const setVariate_message = getMessage('ProcessManage.setVariate_message');
    const setVariate_name_message = getMessage('ProcessManage.setVariate_name_message');
    childNode =
      editing && variateId === record.id ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={
            required
              ? dataIndex === 'varName'
                ? [
                  {
                    required: true,
                    message: setVariate_name_message,
                  },
                  {
                    pattern: /^[a-zA-Z][a-zA-Z\d]*$/,
                    message: setVariate_message,
                  },
                  {
                    message: nameLengthMessage, max: 32
                  }
                ]
                : [
                  {
                    required: true,
                    message: setVariate_name_message,
                  },
                ]
              : []
          }
        >
          {['varName', 'remark'].includes(dataIndex) ? (
            <Input ref={inputRef} onPressEnter={save} onBlur={save} placeholder={placeMessage} />
          ) : ['pcControlId'].includes(dataIndex) ? (
            <Select ref={inputRef} onBlur={save} allowClear placeholder={placeMessage}>
              {pcControl.map((item: any) => {
                return <Select.Option value={item.value}>{item.name}</Select.Option>;
              })}
            </Select>
          ) : ['moveControlId'].includes(dataIndex) ? (
            <Select ref={inputRef} onBlur={save} allowClear placeholder={placeMessage}>
              {h5Control.map((item: any) => {
                return <Select.Option value={item.value}>{item.name}</Select.Option>;
              })}
            </Select>
          ) : null}
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          id={`cell-${dataIndex}-${record.id}`}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
  }

  return <td {...restProps}>{childNode}</td>;
};

export { EditableRow, EditableCell };
